package com.jsp.servlet; /**
 * @author wzm
 * @create 2023-03-10 11:24
 */

import com.jsp.entity.Employee;
import com.jsp.service.EmployeeService;
import com.jsp.service.impl.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addEmp")
public class AddServlet extends HttpServlet {
    private EmployeeService employeeService = new EmployeeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行");

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //介绍参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String age = request.getParameter("age");
        String phone = request.getParameter("phone");
        String status = request.getParameter("status");

        //封装称为一个对象  可以BeanUtils
        Employee employee = new Employee(
                username,password,
                Integer.parseInt(age),
                phone,
                Integer.parseInt(status)
        );

        //调用Service增加
        boolean b = employeeService.saveEmp(employee);
//        b=false;

        //判断结果并返回
        if(b){
            //成功 查询查询全部并渲染  转发地址不会改变 导致重复提交
            //request.getRequestDispatcher("/getAll").forward(request,response);

            //重定向 给页面用的/没有项目名
            response.sendRedirect(request.getContextPath()+"/getAll");

        }else{
            //失败
            //存储信息
            request.setAttribute("error","新增失败请重新尝试");
            request.getRequestDispatcher("emp_add.jsp").forward(request,response);
        }

    }
}
